﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Psm.Util;
using Psm.PubSub.Messaging;

namespace Psm.PubSub.Serialization.Prefixed
{
    public sealed class StringMessageDeserializer
    {
        private int _currentIndex;
        private ByteBuffer _buffer = null;

        public StringMessageDeserializer(ByteBuffer buffer, int padding = 1)
        {
            _buffer = buffer;
            _currentIndex = buffer.StartIndex + padding;
        }

        public PubSubMessageType GetMessageType()
        {
            return (PubSubMessageType)_buffer.GetBuffer()[0];
        }

        public bool HasMore()
        {
            return _currentIndex <= _buffer.EndIndex;
        }

        public string GetField()
        {
            return GetStringValue();
        }

        public void GetTuple(out int item1, out string item2)
        {
            item1 = GetIntValue();
            item2 = GetStringValue();
        }

        public void GetTuple(out string item1, out string item2, out string item3)
        {
            item1 = GetStringValue();
            item2 = GetStringValue();
            item3 = GetStringValue();
        }

        private string GetStringValue()
        {
            int length = GetIntValue();
            string data = ASCIIEncoding.ASCII.GetString(_buffer.GetBuffer(), _currentIndex, length);
            _currentIndex += length;
            return data;
        }

        private int GetIntValue()
        {
            int value = BitConverter.ToInt32(_buffer.GetBuffer(), _currentIndex);
            _currentIndex += 4;
            return value;
        }

    }
}
